﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using Centido.Core.Dto;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Centido.Core.Test
{
    /// <summary>
    ///   Testing the data transfer object for an table index.
    /// </summary>
    [TestClass]
    public class IndexDtoTest : GenericDtoTest
    {
        /// <summary>
        ///   The current domain name.
        /// </summary>
        public const string DomainName = "FullAdminRights";

        /// <summary>
        ///   The current domain.
        /// </summary>
        private Domain _domain;

        /// <summary>
        ///   The table.
        /// </summary>
        private Table _table;

        /// <summary>
        /// Test initialiaze
        /// </summary>
        [TestInitialize]
        public void Initialize()
        {
            _domain = Domain.Build(DomainConfiguration.Load(DomainName));

            _domain.DeleteAll();

            _table = _domain.AddTable(StringProperty.RandomIdentifier());
        }

        /// <summary>
        /// Test clean up
        /// </summary>
        [TestCleanup]
        public void CleanUp()
        {
            _domain.DeleteAll();
        }


        /// <summary>
        ///   Retrieves the name of the data transfer object xml tag.
        /// </summary>
        /// <returns></returns>
        protected override string GetXmlTag()
        {
            return IndexDto.XmlTag;
        }


        /// <summary>
        ///   Retrives the current xml schema version.
        /// </summary>
        /// <returns></returns>
        protected override string GetCurrentXmlSchemaVersion()
        {
            return IndexDto.CurrentXmlSchemaVersion;
        }


        /// <summary>
        ///   Creates a new data transfer object.
        /// </summary>
        /// <returns></returns>
        protected override DataTransferObject CreateDto()
        {
            return new IndexDto
            {
                IsUnique = true
            };
        }


        /// <summary>
        ///   Retrieves the list of data transfer object fields.
        /// </summary>
        /// <returns></returns>
        protected override IEnumerable<DtoFieldInfo> GetFields()
        {
            yield return new DtoFieldInfo
            {
                Name = "IsUnique",
                XmlName = IndexDto.IsUniqueAttribute,
                IsRequired = false,
                FieldType = DtoFieldType.Boolean,
                SampleValue = true,
                IsCopiedFromDto = false
            };
        }


        /// <summary>
        ///   Copies the properties of the data transfer object to the corresponding object.
        /// </summary>
        /// <param name="dto">The data transfer object.</param>
        /// <returns>Returns the corresponding object after copying.</returns>
        protected override object CopyFrom(DataTransferObject dto)
        {
            return null;
        }


        /// <summary>
        ///   Creates a data transfer object from the correpsonding object.
        /// </summary>
        /// <param name="dto">The created data transfer object.</param>
        /// <param name="initialObject">The initial object.</param>
        protected override void CreateDtoFromObject(out DataTransferObject dto, out object initialObject)
        {
            var index = _table.AddIndex(_table.SystemColumns.Owner);

            dto = IndexDto.CreateFrom(index);
            initialObject = index;
        }


        /// <summary>
        ///   Reading the index column list from xml.
        /// </summary>
        [TestMethod]
        public void ReadingColumnListFromXml()
        {
            // Creating the index
            var xml = string.Format("<{0}>",
                IndexDto.XmlTag);

            // Creating the column list
            xml += string.Format("<{0}><{1} {2}=\"{3}\" /><{4} {5}=\"{6}\"></{7}></{8}></{9}>",
                IndexDto.ColumnListTag,
                IndexDto.ColumnTag,
                IndexDto.ColumnNameAttribute,
                StringProperty.RandomIdentifier(),
                IndexDto.ColumnTag,
                IndexDto.ColumnNameAttribute,
                StringProperty.RandomIdentifier(),
                IndexDto.ColumnTag,
                IndexDto.ColumnListTag,
                IndexDto.XmlTag);

            var stream = new XmlTextReader(new MemoryStream(Encoding.UTF8.GetBytes(xml)));

            var indexDto = new IndexDto();

            indexDto.ReadXml(stream);

            Assert.AreEqual(indexDto.ColumnNames.Count(), 2);
        }


        /// <summary>
        ///   Reading an empty column list from xml.
        /// </summary>
        [TestMethod]
        public void ReadingEmptyColumnListFromXml()
        {
            var xml = string.Format("<{0}>",
                IndexDto.XmlTag);

            // Creating the empty column list
            xml += string.Format("<{0} /></{1}>",
                IndexDto.ColumnListTag,
                IndexDto.XmlTag);

            var stream = new XmlTextReader(new MemoryStream(Encoding.UTF8.GetBytes(xml)));

            var indexDto = new IndexDto();

            indexDto.ReadXml(stream);

            Assert.AreEqual(indexDto.ColumnNames.Count(), 0);
        }


        /// <summary>
        ///   Writing and reading the index column list.
        /// </summary>
        [TestMethod]
        public void WritingAndReadingColumnList()
        {
            var indexDto = new IndexDto
            {
                IsUnique = true
            };

            indexDto.AddColumn("a");
            indexDto.AddColumn("b");

            var memoryStream = new MemoryStream();
            var writer = new XmlTextWriter(memoryStream, Encoding.UTF8);

            indexDto.WriteXml(writer);

            writer.Flush();

            memoryStream.Position = 0;
            var streamReader = new StreamReader(memoryStream);
            var xml = streamReader.ReadToEnd();

            Assert.IsFalse(string.IsNullOrEmpty(xml));

            memoryStream.Position = 0;
            var reader = new XmlTextReader(memoryStream);

            var readIndexDto = new IndexDto();

            readIndexDto.ReadXml(reader);

            Assert.AreEqual(readIndexDto.ColumnNames.Count(), 2);
            Assert.AreEqual(readIndexDto.ColumnNames.Count(c => c == "a"), 1);
            Assert.AreEqual(readIndexDto.ColumnNames.Count(c => c == "b"), 1);
        }
    }
}
